<template>
  <div class="components-container">
    <div class="filter-container search-layout">
      <div class="input-container">
        <el-input
          placeholder="请输入属性名称"
          v-model="tableQuery.attributeName"
          style="width: 200px;"
          class="filter-item"
        ></el-input>
        <el-select
          v-model="tableQuery.tagId"
          clearable
          style="width: 200px;"
          class="filter-item"
          placeholder="属性标签"
        >
          <el-option
            v-for="(item, index) in map['analysis.type']"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          v-model="tableQuery.status"
          style="width: 200px;"
          class="filter-item"
          clearable
          placeholder="请选择状态"
        >
          <el-option
            v-for="(item, index) in map['status']"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </div>
      <div class="input-container">
        <el-button size="small" @click="handleFilter" type="primary">
          <i class="el-icon-search"></i>
        </el-button>
        <el-button size="small" @click="handleReset" plain>
          <i class="el-icon-refresh"></i>
        </el-button>
        <el-button size="small" @click="showDialog('create')" plain
          >创建</el-button
        >
      </div>
    </div>
    <Tips :tips="tips" />
    <el-table
      :data="tableData"
      v-loading.body="tableLoading"
      element-loading-text="拼命加载中"
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        align="center"
        label="ID"
        prop="id"
        width="100px"
      ></el-table-column>
      <el-table-column
        align="center"
        label="编码"
        prop="attributeKey"
      ></el-table-column>
      <el-table-column
        align="center"
        label="名称"
        prop="attributeName"
      ></el-table-column>
      <el-table-column
        align="center"
        label="描述"
        prop="attributeDesc"
      ></el-table-column>
      <el-table-column align="center" label="标签">
        <template slot-scope="scope">
          <span
            v-for="(item, index) in scope.row.tags"
            :key="index"
            style="margin-right: 5px;"
            >{{ item.analysisName }}</span
          >
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <span>{{ statusOptions[scope.row.status] }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="版本" prop="version"></el-table-column> -->
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <a
            size="mini"
            class="click-btn"
            @click="showDialog('update', scope.row)"
            type="primary"
            style="margin-right: 10px;"
            >编辑</a
          >
          <a
            size="mini"
            class="click-btn"
            @click="handleUsedAge(scope.row)"
            type="primary"
            >使用情况</a
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container" style="padding: 5px 0;">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="tableQuery.pageNo"
        :page-sizes="[10, 20, 50]"
        :page-size="tableQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-dialog
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :title="formTitle"
      :visible.sync="formVisible"
      width="600px"
    >
      <el-form
        class="small-space"
        :model="createdItem"
        label-position="right"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="编码">
          <el-input
            size="small"
            v-model="createdItem.attributeKey"
            :disabled="disabledStatus"
            placeholder="请输入编码"
            maxlength="50"
            style="width: 260px"
          ></el-input>
        </el-form-item>
        <el-form-item label="名称">
          <el-input
            size="small"
            v-model="createdItem.attributeName"
            :disabled="disabledStatus"
            placeholder="请输入名称"
            maxlength="50"
            style="width: 260px"
          ></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            size="small"
            type="textarea"
            v-model="createdItem.attributeDesc"
            placeholder="请输入描述"
            style="width: 260px"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="createdItem.status"
            size="small"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in map['status']"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="属性标签">
          <el-select
            v-model="createdItem.tags"
            size="small"
            clearable
            multiple
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in map['analysis.type']"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抽取逻辑">
          <el-select
            v-model="createdItem.extractType"
            size="small"
            placeholder="请选择"
          >
            <el-option
              v-for="(item, index) in sqlOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-input
            size="small"
            type="textarea"
            v-model="createdItem.sqlScript"
            placeholder="请输入SQL脚本"
            style="width: 260px"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="close">取 消</el-button>
        <el-button
          size="small"
          type="primary"
          @click="save"
          :loading="formSubmit"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :title="formTitle"
      :visible.sync="usedAgeFormVisible"
      width="70%"
    >
      <div class="form-container">
        <span class="filter-txt">编码：</span>
        <span>{{ usedAgeData.attributeKey }}</span>
      </div>
      <div class="form-container">
        <span class="filter-txt">名称：</span>
        <span>{{ usedAgeData.attributeName }}</span>
      </div>
      <div class="form-container">
        <span class="filter-txt">描述：</span>
        <span>{{ usedAgeData.attributeDesc }}</span>
      </div>
      <div class="be-used">被使用</div>
      <el-table
        :data="usedAgeTableData"
        v-loading.body="tableLoading"
        element-loading-text="拼命加载中"
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column
          align="center"
          label="事件编码"
          prop="eventKey"
        ></el-table-column>
        <el-table-column
          align="center"
          label="事件名"
          prop="eventName"
        ></el-table-column>
      </el-table>
      <div class="pagination-container" style="padding: 5px 0;">
        <el-pagination
          background
          @size-change="handleUsedAgeSizeChange"
          @current-change="handleUsedAgeCurrentChange"
          :current-page.sync="usedAgeTableQuery.pageNo"
          :page-sizes="[10, 20, 50]"
          :page-size="usedAgeTableQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="usedAgeTotal"
        ></el-pagination>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="closeUsedAge"
          >关闭</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapList } from '@/api/report/common'
import * as api from '@/api/report/attributes'
import { userLog } from '@/api/report/events'
import Tips from '@/views/report/Components/Tips/index'

const defaultPage = {
  pageSize: 10,
  pageNo: 1
}
const defaultTableQuery = {
  tagId: null,
  status: null,
  attributeName: null
}
const defaultCreateQuery = {
  attributeKey: '',
  attributeName: null,
  attributeDesc: '',
  status: null,
  tags: '',
  extractType: 1,
  sqlScript: ''
}
export default {
  data() {
    return {
      // 操作提示

      map: {},
      tips: {
        text: ''
      },

      sqlOptions: [{ label: 'SQL', value: 1 }],

      // 查询条件，创建、编辑表单参数
      tableQuery: Object.assign({}, defaultTableQuery, defaultPage),
      createdItem: Object.assign({}, defaultCreateQuery),

      total: null,
      tableData: [],
      tableLoading: true,

      // 创建、编辑
      formTitle: '',
      formVisible: false,
      formSubmit: false,

      // 使用情况
      usedAgeFormVisible: false,
      usedAgeTableQuery: Object.assign({}, defaultPage),
      usedAgeData: {},
      usedAgeTableData: [],
      usedAgeTotal: null
    }
  },
  created() {
    this.getList()
    this.getMapConfig()
  },
  mounted() {},
  computed: {
    /* map() {
      return this.mapConfig
    }, */
    statusOptions() {
      let options = {}
      let statusMap = this.map['status'] || []
      statusMap.forEach(item => {
        Object.assign(options, {
          [item.value]: item.label
        })
      })
      return options
    },
    disabledStatus() {
      if (this.createdItem.id) {
        return true
      }
      return false
    }
  },
  components: {
    Tips
  },
  methods: {
    getMapConfig() {
      mapList({
        types: [
          'table_column.value_type',
          'report.calc_type',
          'report.number.operation_type',
          'report.sort_type',
          'report.datetime.unit',
          'analysis.type',
          'status',
          'event.type',
          'event.tags',
          'event.list',
          'page.type',
          'page.list',
          'widget.type'
        ]
      })
        .then(data => {
          this.map = Object.assign({}, this.map, data.data)
        })
        .catch(error => {
          console.error(error)
        })
    },
    handleFilter() {
      this.tableQuery.pageNo = 1
      this.getList()
    },

    handleReset() {
      this.tableQuery = Object.assign({}, defaultTableQuery, defaultPage)
      this.getList()
    },

    // 获取列表
    getList() {
      this.tableLoading = true
      api
        .list({
          data: this.tableQuery
        })
        .then(response => {
          this.tableLoading = false
          let { records, total } = response.data
          this.tableData = records
          this.total = total
        })
        .catch(error => {
          console.log(error)
          this.tableLoading = false
          Object.assign(this.tips, {
            show: true,
            text: error,
            type: 'error'
          })
        })
    },

    handleSizeChange(val) {
      this.tableQuery.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.tableQuery.pageNo = val
      this.getList()
    },

    // 新增，修改弹窗
    showDialog(type, row = null) {
      this.formVisible = true
      this.formSubmit = false
      this.clearDialog()
      if (type === 'create') {
        this.formTitle = '创建'
        this.createdItem.tags = []
      } else {
        this.formTitle = '编辑'
        for (var i in this.createdItem) {
          this.createdItem[i] = row[i]
        }
        this.createdItem.tags = row['tags'].map(item => {
          return item.id
        })
        this.createdItem['id'] = row['id'] ? row['id'] : ''
        console.log(this.createdItem)
      }
    },

    // 获取使用情况table数据
    getUsedAgeList() {
      userLog({
        data: this.usedAgeTableQuery
      })
        .then(response => {
          this.tableLoading = false
          let { records, total } = response.data

          this.usedAgeTotal = total
          this.usedAgeTableData = records
          console.log(this.usedAgeTableData)
        })
        .catch(error => {
          console.log(error)
          this.tableLoading = false
          this.$message.error(error)
        })
    },

    // 使用情况
    handleUsedAge(row) {
      this.formTitle = '使用情况'
      this.usedAgeFormVisible = true
      this.usedAgeTableQuery = Object.assign({}, defaultPage)
      this.usedAgeTableQuery.id = row.id
      this.usedAgeData = Object.assign(
        {},
        {
          attributeKey: row.attributeKey,
          attributeName: row.attributeName,
          attributeDesc: row.attributeDesc
        }
      )
      this.getUsedAgeList()
    },

    handleUsedAgeSizeChange(val) {
      this.usedAgeTableQuery.pageSize = val
      this.getUsedAgeList()
    },

    handleUsedAgeCurrentChange(val) {
      this.tableQuery.pageNo = val
      this.getUsedAgeList()
    },

    closeUsedAge() {
      this.usedAgeFormVisible = false
    },

    // 创建，编辑初始化弹窗
    clearDialog() {
      this.createdItem = Object.assign({}, defaultCreateQuery)
    },

    close() {
      this.formVisible = false
    },

    // 验证必填项
    validate() {
      let {
        attributeKey,
        attributeName,
        attributeDesc,
        status,
        tags
      } = this.createdItem
      if (!attributeKey) {
        this.$message.error('请填写编码')
        return true
      }
      if (!attributeName) {
        this.$message.error('请填写名称')
        return true
      }
      if (!attributeDesc) {
        this.$message.error('请填写描述')
        return true
      }
      if (status === '' || status === undefined || status === null) {
        this.$message.error('请选择状态')
        return true
      }
      if (!tags.length) {
        this.$message.error('请选择属性标签')
        return true
      }
      return false
    },

    // 创建，编辑
    save() {
      if (this.validate()) return
      let type = this.createdItem.id ? 'update' : 'create'
      let data = {}
      data = Object.assign({}, this.createdItem, {
        tags: this.createdItem.tags.toString()
      })

      this.formSubmit = true
      api[type]({
        data: data
      })
        .then(response => {
          this.close()
          this.getList()
        })
        .catch(error => {
          this.$message.error(error)
          this.formSubmit = false
        })
    }
  }
}
</script>

<style lang="scss">
@import './less/index.scss';
</style>
